export const formatTime = (date: Date) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return (
    [year, month, day].map(formatNumber).join('/') +
    ' ' +
    [hour, minute, second].map(formatNumber).join(':')
  )
}

const formatNumber = (n: number) => {
  const s = n.toString()
  return s[1] ? s : '0' + s
}

export const handleCode = (res: Object, msg = '') => {
  wx.showToast({
    title: res.code === 0 ? msg : (res.msg || '失败'),
    icon: res.code === 0 ? 'success' : 'error',
    duration: 1500
  })
}

export const handleErrCode = (msg = '失败', icon = 'none') => {
  wx.showToast({
    title: msg,
    icon: icon,
    duration: 1500
  })
}

export const calculateDaysAgo = (dateString: string) => {
  const now = new Date().getTime()
  const createTime = new Date(dateString).getTime()
  const diff = now - createTime
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  if (days === 0) {
    return '今天'
  } else {
    return days + '天前'
  }
}
/**
 * 防抖
 * @param fn 需要防抖的函数
 * @param t 时间
 */
export const debounce = (fn, t) => {
  let timeId = null
  const delay = t
  return function (this, ...args) {
    if (timeId) {
      clearTimeout(timeId)
    }
    timeId = setTimeout(() => {
      timeId = null
      fn.apply(this, args)
    }, delay)
  }
}

/**
 * 节流
 * @param fn 需要节流的函数
 * @param t 时间
 */
export const throttle = (ft, t) => {
  let flag = true
  const interval = t
  return function (this, ...args) {
    if (flag) {
      fn.apply(this, args)
      flag = false
      setTimeout(() => {
        flag = true
      }, interval)
    }
  }
}